#include "SN74AHC595.h"

// ShiftRegister74HC595 constructor
// Size is the number of shiftregisters stacked in serial
using namespace ti;

SN74AHC595::SN74AHC595(PinName pin_oe,PinName  pin_srclk,PinName  pin_ser,PinName pin_rclk,uint8_t * digitalValues):
    _oe(pin_oe),
    _srclk(pin_srclk),
    _ser(pin_ser),
    _rclk(pin_rclk),
    _digitalValues(digitalValues)
{

    _srclk= 0;
    _ser=0;
    _rclk=0;
    if(_digitalValues==nullptr){
        _digitalValues = _data;
    }
}

void SN74AHC595::begin(uint8_t * digitalValues)
{
    if(digitalValues!=nullptr){
        _digitalValues = digitalValues;
    }
    this->set_oe(true);
}
void SN74AHC595::set_oe(bool en)
{
    (en==true) ? (_oe = 0): (_oe = 1);
}

void SN74AHC595::shift_out( uint8_t bitOrder, uint8_t val)
{
	uint8_t i;

	for (i = 0; i < 8; i++)  {
		if (bitOrder == LSBFIRST) {
			_ser = val & 1;
			val >>= 1;
		} else {	
            //_ser.write(((val & 128) != 0)?1:0);
            _ser = ((val & 128) != 0)?1:0;
			val <<= 1;
		}
			
		_srclk=1;
		_srclk=0;		
	}
}

void SN74AHC595::updateRegisters(int size)
{
    if(_digitalValues==nullptr){
        return;
    }
    
    for (int i = size - 1; i >= 0; i--) {
        this->shift_out(MSBFIRST, _digitalValues[i]);
    }
    
    _rclk=1; 
    _rclk=0; 
}
